#include "pch.h"
#include "CLog.h"
#include "string.h"
CLog::CLog()
{
	TCHAR  moduleFileName[MAX_PATH];
	::GetModuleFileName(NULL, moduleFileName, MAX_PATH);
	(_tcsrchr(moduleFileName, _T('\\')))[1] = 0;
	CString strPath = moduleFileName;
	strPath.Append(_T("\\data\\"));
	if (!_wmkdir(strPath))
	{
		//TODO
	}
	//strPath.Append(_T("\\log\\"));
	m_Path = strPath.GetString();
	//if (!_wmkdir(m_Path.c_str()))
	//{
		//TODO
	//}
	//m_Path = L"";
	::InitializeCriticalSection(&m_csLogger);
}

CLog::CLog(CString path)
{
	m_Path = path;
	::InitializeCriticalSection(&m_csLogger);
}

CLog::~CLog()
{
	::DeleteCriticalSection(&m_csLogger);
}

void CLog::SetUI(HWND ui)
{
	m_UI = ui;
}

void CLog::DisplayAndSaveLog(std::wstring msg, eEVENT_LEVEL level)
{
	::EnterCriticalSection(&m_csLogger);
	SYSTEMTIME ti;
	::GetLocalTime(&ti);
	CString strtime;
	strtime.Format(L"%02d:%02d:%02d:%03d",ti.wHour,ti.wMinute,ti.wSecond,ti.wMilliseconds);
	std::wstring time = strtime.GetString();
	std::wstring lastlog= time+L"#"+msg;
	m_dictLogMsg.insert(std::pair<std::wstring,std::wstring>(time,lastlog));
	::LeaveCriticalSection(&m_csLogger);
	CString str = lastlog.c_str();
	BSTR string=str.AllocSysString();
	::SendMessage(m_UI, WM_SEND_LOG_TO_UI,(WPARAM)string,level);
	Save();
}
CMutex cMutlog(false, NULL);
void CLog::Save()
{
	std::multimap<std::wstring, std::wstring>tmpmsg;
	::EnterCriticalSection(&m_csLogger);
	tmpmsg = m_dictLogMsg;
	m_dictLogMsg.clear();
	::LeaveCriticalSection(&m_csLogger);
	if (tmpmsg.empty())
	{
		return;
	}
	SYSTEMTIME ti;
	::GetLocalTime(&ti);
	CString str;
	str.Format(L"%d-%02d-%02d",ti.wYear,ti.wMonth,ti.wDay);
	std::wstring logfile = m_Path + L"\\" + str.GetString() + L".log";

	std::string strFile = Unicode2Ansi(logfile);
	cMutlog.Lock();
	FILE* fp1 = nullptr;

	
	fopen_s(&fp1, strFile.c_str(), "a");
	for (auto it = tmpmsg.begin(); it != tmpmsg.end(); it++)
	{
		std::string strLog = Unicode2Ansi(it->second);
		fputs(strLog.c_str(), fp1);
		fputs("\r\n", fp1);
	}
	
	fclose(fp1);
	cMutlog.Unlock();
	return;
}
